package com.jbit.examSystem.service.impl;

import com.jbit.examSystem.dao.TeacherDao;
import com.jbit.examSystem.dto.UserDto;
import com.jbit.examSystem.exception.LoginErrorException;
import com.jbit.examSystem.pojo.Teacher;
import com.jbit.examSystem.pojo.User;
import com.jbit.examSystem.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class TeacherServiceImpl implements TeacherService {
    @Autowired
    private TeacherDao teacherDao;

    @Override
    public void register(UserDto userDto) {
        Teacher teacher = createTeacher(userDto);
        teacherDao.add(teacher);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Teacher checkEmail(String email) {
        //判断邮箱是否已被注册
        Teacher teacher = teacherDao.checkEmail(email);
        return teacher;
    }

    private Teacher createTeacher(UserDto userDto) {
        Teacher teacher = new Teacher();
        teacher.setEmail(userDto.getEmail());
        teacher.setIdentityId(userDto.getIdentityId());
        teacher.setName(userDto.getName());
        teacher.setPassword(userDto.getPassword());
        teacher.setPhone(userDto.getPhone());
        teacher.setImagePath("http://localhost/head-portrait/default.jpg");

        return teacher;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Teacher login(UserDto userDto) throws LoginErrorException {
        String name = userDto.getName();
        String password = userDto.getPassword();

        Teacher teacher = teacherDao.loginByNameAndPassword(name, password);
        if (teacher == null){
            throw new LoginErrorException("登录失败，用户名或密码错误!");
        }
        return teacher;
    }

    @Override
    public void setLoginTime(Date loginTime, Integer id, Date lastLoginTime) {
        teacherDao.setLoginTime(loginTime,id,lastLoginTime);
    }

    @Override
    public void updateInfo(User user) {
        teacherDao.updateInfo(user);
    }

    @Override
    public Teacher findById(Integer id) {
        return teacherDao.selectById(id);
    }

    @Override
    public List<Teacher> findAll() {
        return teacherDao.selectAll();
    }

    @Override
    public List<User> getAllTeacher(String userName) {
        List<User> user = teacherDao.getAllTeacher(userName);
        return user;
    }
}
